package com.springboot.erp.service.impl;

import com.springboot.erp.entity.IncomeDTO;
import com.springboot.erp.entity.JshAccountHead;
import com.springboot.erp.mapper.IncomeMapper;
import com.springboot.erp.service.IncomeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class IncomeServiceImpl implements IncomeService {
    @Resource
    private IncomeMapper incomeMapper;

    @Override
    public IncomeDTO selectIncomeById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("查询收入单时，ID不能为空");
        }
        // 直接返回查询结果，允许返回null
        return incomeMapper.selectIncomeById(id);
    }

    @Override
    public List<JshAccountHead> listIncomes(Long organId, String status, Date startDate, Date endDate) {
        // 校验日期范围是否合理
        if (startDate != null && endDate != null && startDate.after(endDate)) {
            throw new IllegalArgumentException("查询收入单列表时，开始日期不能晚于结束日期");
        }
        return incomeMapper.selectIncomeList(organId, status, startDate, endDate);
    }

    @Override
    public void addOne(JshAccountHead jshAccountHead) {
        // 校验必填字段
        if (jshAccountHead.getBillNo() == null || jshAccountHead.getTotalPrice() == null) {
            throw new IllegalArgumentException("添加收入单时，单据编号和总金额为必填项");
        }
        incomeMapper.insertOne(jshAccountHead);
    }

    @Override
    public void updateOne(JshAccountHead jshAccountHead) {
        if (jshAccountHead.getId() == null) {
            throw new IllegalArgumentException("更新收入单时，ID不能为空");
        }
        // 自行判断数据是否存在
        IncomeDTO income = selectIncomeById(Long.valueOf(jshAccountHead.getId()));
        if (income == null) {
            log.warn("更新失败：ID为{}的收入单不存在", jshAccountHead.getId());
            return; // 或返回特定结果（如false）
        }
        incomeMapper.updateOne(jshAccountHead);
    }

    @Override
    public void deleteOne(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("删除收入单时，ID不能为空");
        }
        // 自行判断数据是否存在
        IncomeDTO income = selectIncomeById(id.longValue());
        if (income == null) {
            log.warn("删除失败：ID为{}的收入单不存在", id);
            return; // 或返回特定结果（如false）
        }
        incomeMapper.deleteOne(id);
    }
}




